package com.hjq.fcloud.utils;

import androidx.annotation.NonNull;

import com.hjq.fcloud.aop.Log;
import com.hjq.fcloud.app.AppActivity;
import com.hjq.fcloud.app.AppApplication;
import com.hjq.fcloud.ui.activity.CommonPdfViewActivity;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.OnDownloadListener;
import com.hjq.http.model.HttpMethod;
import com.hjq.toast.ToastUtils;

import java.io.File;

public class FileDownloadUtils {

    //下载目录
    public static final String DOWNLOAD_FILE_DIR = "FCloud";

    @NonNull
    private static File getFullFile(String url) {
        String fileName = FileUtils.getFileName(url);
        File storeFile = new File(AppApplication.mContext.getCacheDir() + File.separator + DOWNLOAD_FILE_DIR + File.separator, fileName);
        return storeFile;
    }

    private static void startDownLoad(AppActivity context, final String url, final File file) {
        int progress = 0;
        String contentMsg = "正在下载中 ";
        context.showProgressDialog(contentMsg + +progress + "%");
        EasyHttp.download(context)
                .method(HttpMethod.GET)
                .file(file)
                .url(url)
//                .url("http://dldir1.qq.com/weixin/android/weixin708android1540.apk")
//                .url("http://fir.dhb168.com/gpzn?release_id=62372664b2eb4620ff7960ab")
                .listener(new OnDownloadListener() {

                    @Override
                    public void onStart(File file) {
                    }

                    @Override
                    public void onProgress(File file, int progress) {
                        context.showProgressDialog(contentMsg + progress + "%");
                        Logger.i("--->>>startDownLoad progress:"+progress);
                    }

                    @Override
                    public void onComplete(File file) {
                        openFileByPdfView(context, file.getAbsolutePath());
                    }

                    @Override
                    public void onError(File file, Exception e) {
                        ToastUtils.show("下载出错：" + e.getMessage());
                    }

                    @Override
                    public void onEnd(File file) {
                        context.hideProgressDialog();
                    }

                }).start();
    }

    /**
     * 文件查看或下载
     * 检查存在则查看，否则
     *
     * @param context
     * @param url
     */
    public static void filePreviewOrDownload(AppActivity context, String url) {
        try {
            File file = getFullFile(url);
            if (file.exists()) {
                openFileByPdfView(context, file.getAbsolutePath());
            } else {
                startDownLoad(context, url, file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void openFileByPdfView(AppActivity context, String path) {
        CommonPdfViewActivity.Companion.start(context,path);
    }
}
